<?php
namespace app\home\controller;

use app\common\component\user\UserService;
use app\common\component\user\UserValidate;

class UserInfo extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		if($this -> request -> isPost()) {
			$resultUpdateUser = $this -> update();
			if($resultUpdateUser['code'] !== 0) {
				$this -> error($resultUpdateUser['message']);
			}

			echo '<meta charset="utf-8"><script>alert("修改成功!");window.history.go(-1);</script>';exit;
		}

		$userService = new UserService;
		$resultUser = $userService -> getUser();
		if($resultUser['data']['user']['promotion_id'] !== 0) {
			$getPromotion = $userService -> getUser($resultUser['data']['user']['promotion_id']);
			if($getPromotion['code'] === 0) {
				$resultUser['data']['user'] -> promotion_name = $getPromotion['data']['user'] -> username;
			} else {
				$resultUser['data']['user'] -> promotion_name = '无推荐人';
			}
		} else {
			$resultUser['data']['user'] -> promotion_name = '无推荐人';
		}

		if($resultUser['code'] === 0) {
			$this -> view -> assign('user', $resultUser['data']['user']);
		}
		return $this -> view -> fetch();
	}

	public function update() {
		$post = $this -> request -> post();

		$resultUserValidate = (new UserValidate) -> update($post);
		if($resultUserValidate['code'] !== 0) {
			$this -> error($resultUserValidate['message']);
		}

		return (new UserService) -> update($post);
		
	}

	public function changePassword() {
		if($this -> request -> isPost()) {
			$post = $this -> request -> post();

			if(isset($post['old_password'])) {
				$resultUserValidate = (new UserValidate) -> checkPassword($post);

				$save['password'] = getPasswordHash($post['new_password']);
			} else if(isset($post['old_pay_password'])) {
				$resultUserValidate = (new UserValidate) -> checkPayPassowrd($post);

				$save['pay_password'] = getPasswordHash($post['new_pay_password']);
			} else {
				$resultUserValidate['code'] = -1;
				$resultUserValidate['message'] = '非法操作!';
			}

			if($resultUserValidate['code'] !== 0) {
				$this -> error($resultUserValidate['message']);
			}

			$resultUserUpdate = (new UserService) -> update($save);
			if($resultUserUpdate['code'] !== 0) {
				$this -> error($resultUserUpdate['message']);
			}
			echo '<meta charset="utf-8"><script>alert("修改成功!");window.history.go(-1);</script>';exit;
		}

		return $this -> view -> fetch();
	}

	public function link() {
		return $this -> view -> fetch();
	}
}